package com.none.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.none.usercenter.common.ErrorCode;
import com.none.usercenter.excption.BusinessException;
import com.none.usercenter.mapper.UserMapper;
import com.none.usercenter.model.domain.User;
import com.none.usercenter.service.UserService;
import com.none.usercenter.utils.AlgorithmUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.none.usercenter.contant.UserConstant.ADMIN_ROLE;
import static com.none.usercenter.contant.UserConstant.USER_LOGIN_SATE;

/**
* @author xiaofeng
* @description 针对表【user(user)】的数据库操作Service实现
* @createDate 2025-10-14 23:07:05
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    //定义盐值,混淆密码
    private static final String SALT = "";

    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String password, String checkPassword,String planetCode) {
        //校验
        //1.非空
        if(StringUtils.isAnyBlank(userAccount,password,checkPassword,planetCode)) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if (planetCode.length() > 5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户账号过短");
        }
        //2.账号不效于4位，密码不小于8位
        if (userAccount.length() < 4 || password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编号过长");
        }
        //3.不能包含特殊字符
        String regex = "^[a-zA-Z0-9]+$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if(!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不能包含特色字符");
        }

        //4.密码和校验密码相同
        if(!checkPassword.equals(password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次输入密码不同");
        }
        //5.账户不能重复
        //MyBatis-Plus的条件构造器，用于构建SQL查询条件
        QueryWrapper queryWrapper = new QueryWrapper<>();
        //添加查询条件：user_account字段等于指定的userAccount值
        queryWrapper.eq("user_account", userAccount);
        //执行统计查询，返回满足条件的记录数量
        long count = this.count(queryWrapper);
        if(count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号已存在");
        }

        //星球编号不能重复
        //MyBatis-Plus的条件构造器，用于构建SQL查询条件
        queryWrapper = new QueryWrapper<>();
        //添加查询条件：user_account字段等于指定的userAccount值
        queryWrapper.eq("planet_code", planetCode);
        //执行统计查询，返回满足条件的记录数量
        count = this.count(queryWrapper);
        if(count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"编号已存在");
        }

        //6. 加密
        //将拼接后的字符串转换为字节数组,解析md5的加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //7. 插入数据
        User user = new User();
        user.setUsername("test");
        user.setGender(1);
        user.setPhone("123456789");
        user.setPlanetCode(planetCode);
        user.setEmail("test@gmail.com");
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean save = this.save(user);
        if(!save) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public User dologin(String userAccount, String password, HttpServletRequest request) {
        //1.非空
        if(StringUtils.isAnyBlank(userAccount,password)) {
            return null;
        }
        //2.账号不效于4位，密码不小于8位
        if (userAccount.length() < 4 || password.length() < 8) {
            return null;
        }
        //3.不能包含特殊字符
        String regex = "^[a-zA-Z0-9]+$";
        Matcher matcher = Pattern.compile(regex).matcher(userAccount);
        if(!matcher.find()) {
            return null;
        }

        //4. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        //5. 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password",encryptPassword);
        System.out.println(queryWrapper);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if (user == null){
            log.info("user login faild,userAccount cannt match usrePassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号密码错误");
        }

        //6. 用户脱敏
        User safetyUser = getSafetyUser(user);
        //7.记录用户的登录状态
        request.getSession().setAttribute(USER_LOGIN_SATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     * @param originalUser
     * @return
     */
    public User getSafetyUser(User originalUser){
        if (originalUser == null){
            return null;
        }
        User cleanUser = new User();
        cleanUser.setId(originalUser.getId());
        cleanUser.setUsername(originalUser.getUsername());
        cleanUser.setUserAccount(originalUser.getUserAccount());
        cleanUser.setAvatarurl(originalUser.getAvatarurl());
        cleanUser.setGender(originalUser.getGender());
        cleanUser.setPhone(originalUser.getPhone());
        cleanUser.setEmail(originalUser.getEmail());
        cleanUser.setUserStatus(originalUser.getUserStatus());
        cleanUser.setCreateTime(originalUser.getCreateTime());
        cleanUser.setUserRole(originalUser.getUserRole());
        cleanUser.setPlanetCode(originalUser.getPlanetCode());
        cleanUser.setTags(originalUser.getTags());
        return cleanUser;
    }

    /**
     * 用户注销
     * @param request
     */
    @Override
    public int userLginOut(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_SATE);
        return 1;
    }

    /**
     * @param tagNameList 用户拥有的标签
     * @return
     */
    @Override
    public List<User> searchUserByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        //拼接and查询
//        // list '%Java%' and like '%Python%'
//        for(String tagName:tagNameList){
//            queryWrapper = queryWrapper.like("tags", tagName);
//        }
//        List<User> userList = userMapper.selectList(queryWrapper);
//        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());

        //先查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        //在内存中判断是否包含要求的标签
        return userList.stream().filter((user)  ->{
            String tagStr = user.getTags();
            if(StringUtils.isBlank(tagStr)){
                return false;
            }
            Set<String> tempTagNameSet = gson.fromJson(tagStr, new TypeToken<Set<String>>() {}.getType());
            tempTagNameSet= Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
                for (String tagName: tagNameList){
                    if(!tagNameList.contains(tagName)){
                        return false;
                    }
                }
                return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    @Override
    public int updateUser(User user,User loginUser) {
        long userId = user.getId();
        if (userId <=0 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //如果是管理员，运行更新任意用户
        //如果是普通用户，只能更新自己的信息
        if (!isAdmin(loginUser) && userId != loginUser.getId()){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        User OldUser = userMapper.selectById(userId);
        if (OldUser == null){
            throw new BusinessException(ErrorCode.NO_ERROR);
        }
        return userMapper.updateById(user);
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null){
            return null;
        }
        Object userObj = request.getSession().getAttribute(USER_LOGIN_SATE);
        if (userObj == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return (User) userObj;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request){
        //仅管理员可查询
        User user =(User) request.getSession().getAttribute(USER_LOGIN_SATE);
        if (user == null || user.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return true;
    }

    @Override
    public boolean isAdmin(User user){
        if (user == null || user.getUserRole() != ADMIN_ROLE){
            return false;
        }
        return true;
    }


    @Override
     public List<User> matchUsers(long num, User loginUser) {
        //过滤标签为空的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //只查想要的列
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户列表的下标 => 相似度
        List<Pair<User, Long>> list = new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            // 无标签或者为当前用户自己
            if (StringUtils.isBlank(userTags) || user.getId() == loginUser.getId()) {
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            // 计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user, distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList = topUserPairList.stream().map(pair -> pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userIdList) {
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }


}




